<template>
    <div class="zc-layout-main-body">
        <el-row :gutter="20">
            <el-col :span="4">
                <el-card class="zc-box-aside">
                    <template #header>
                        <div>
                            <span class="title">数据源</span>
                            <el-button type="primary" class="btn" @click="toCreat" plain>新增</el-button>
                        </div>
                    </template>
                    <el-tree :data="domain.dbms"
                             check-on-click-node
                             :props="{class:doNodeClass}"
                             node-key="id"
                             @current-change="doDbmsSelect">
                        <template #default="{ node, data }">
                          <span>
                            <span>{{ data.name }}</span>
                          </span>
                            <span>
                                 <el-button text type="primary" style="margin-left: 48px" size="small">编辑</el-button>
                            </span>
                        </template>
                    </el-tree>
                </el-card>
            </el-col>
            <el-col :span="20">
                <div class="zc-box-main">
                    <el-tabs v-model="domain.active">
                        <el-tab-pane label="实体模型" name="first">
                            <Function
                                    ref="modeDesignRef"
                                    :list="options.list"
                                    :create="options.create"
                                    :fields="options.fields"
                                    :form-options="options.formOptions"
                                    :operateOptions="options.operateOptions"
                                    :search-options="options.searchOptions"
                            ></Function>
                        </el-tab-pane>
                    </el-tabs>
                </div>
            </el-col>
        </el-row>
    </div>
    <DbmsCreat ref="dbmsRef" @submit="doSubmit"></DbmsCreat>
    <DomainDesign ref="domainDesignRef" @submit="doDomainDesignSubmit" :dbmsId="domain.dbmsId"></DomainDesign>
</template>
<script type="ts" setup>
import {defineAsyncComponent, onBeforeMount, onMounted, reactive, ref} from "vue";
import {ElMessage, ElMessageBox} from "element-plus";
import Function from "@/components/core/function/index.vue";
import {createModel, validateModelName, validateModelTableName, pageModel, executeModel} from "@/api/api.model";
import {listDbms} from "@/api/api.dbms";
import {company} from "@/utils/core/store"
import {app} from "@/utils/core/store"

const DbmsCreat = defineAsyncComponent(() => import('../dbms/create.vue'));
const DomainDesign = defineAsyncComponent(() => import('../domain/design.vue'));
const dbmsRef = ref();
const domainDesignRef = ref();
const modeDesignRef = ref();
const domain = reactive({
    active: 'first',
    dbms: [],
    dbmsId: undefined
})

const doNodeClass = (data, node) => {
    if (data.id === domain.dbmsId) {
        return "zc-selected";
    }
}

const options = reactive({
    list: {
        api: pageModel,
        autoLoad: false,
        fixParams: {companyId: company.value.id, appId: app.value.id, dbmsId: domain.dbmsId},
        sort: 'updateAt_desc;createAt_desc'
    },
    create: {
        api: createModel,
        title: '新增模型'
    },
    operateOptions: {
        operate: {
            display: true,
            width: '200px',
            buttons: [{
                label: '模型设计',
                display: true,
                doClick: (row) => {
                    domainDesignRef.value.openDialog(row);
                }
            }, {
                label: '数据管理',
                display: true,
                doClick: (row) => {

                }
            }, {
                label: '删除',
                display: true,
                doClick: (row) => {

                }
            }]
        }
    },
    formOptions: {
        onBeforeSubmit: (forms) => {
            forms.companyId = company.value.id;
            forms.appId = app.value.id;
            forms.dbmsId = domain.dbmsId;
        },
        onAfterSubmit: (data) => {

            ElMessageBox.confirm('请确定\n' + data.script, '请确定', {
                confirmButtonText: '确认'
            }).then(() => {
                // 执行数据库脚本
                executeModel({id: data.id}).then(res => {
                    if (res.data) {
                        ElMessage.success("更新成功");
                    } else {
                        ElMessage.error("更新失败");
                    }
                }).catch((e) => {
                    ElMessage.error("新增失败:" + e);
                })
            });
        }
    },
    fields: [
        {
            name: 'name',
            label: '模型名称',
            type: 'input',
            required: true,
            showForm: true,
            showList: true,
            validate: validateModelName,
            placeholder: '请输入模型名称'
        },
        {
            name: 'tableName',
            label: '表名',
            type: 'input',
            required: true,
            showForm: true,
            showList: true,
            validate: validateModelTableName,
            placeholder: '请输入表名',
            description: '不可以修改，只允许用字母和下划线'
        },
        {
            name: 'createAt',
            label: '更新时间',
            showList: true
        },
        {
            name: 'updateAt',
            label: '更新时间',
            showList: true
        }

    ],
    searchOptions: {
        params: {},
        operations: [{
            name: 'name',
            text: '请输入模型名称'
        }, {
            name: 'tableName',
            text: '请输入表名'
        }]
    }
})
const toCreat = () => {
    dbmsRef.value.openDialog();
}

const doDbmsSelect = (dbms, node) => {
    domain.dbmsId = dbms.id;
    doLoadModels();
}
const doSubmit = () => {

}

const doSelectFirst = () => {
    if (domain.dbms.length !== 0) {
        domain.dbmsId = domain.dbms[0].id;
        doLoadModels();
    }
}

const doDomainDesignSubmit = () => {

}
const doLoadModels = () => {
    options.list.fixParams.dbmsId = domain.dbmsId;
    modeDesignRef.value.loadData();
}
const loadDbms = async () => {
    await listDbms({companyId: company.value.id})
        .then(res => {
            domain.dbms = res.data || [];
            // 默认选择第一个
            doSelectFirst();
        })
}

onBeforeMount(() => {
    loadDbms();
})
</script>
